<template>
    <div>
        <div class="operation-group">
            <el-button plain type="single-number" @click="chooseSelectDialog('contract')">选择合同</el-button>
            <el-button plain type="single-number" @click="chooseSelectDialog('accept')">选择验收单</el-button>
            <dropdown :dropdown-data="dropdown" @dropDown="dropDown"/>
            <el-button plain type="single-number" @click="hebingFunAuto">合并</el-button>
            <el-button plain type="single-number" @click="handleDelete">删除行</el-button>
        </div>
        <div class="ccui-multifunctional-table-wrapper">
            <ux-grid
                class="ccui-form-child-table"
                keep-source
                widthResize
                width="100%"
                show-overflow="title"
                show-summary
                :summary-method="getSummaries"
                @select="selectTable"
                @select-all="selectTable"
                @selection-change="handleSelectionChange"
                :edit-config="{ trigger: 'click', mode: 'cell' }"
                ref="tableList"
                :checkboxConfig="{ checkMethod: handleSelectableDisabled, highlight: false }"
            >
                
                <ux-table-column
                    type="checkbox"
                    width="55"
                    show-overflow="none"
                    fixed="left"
                />
                
                <ux-table-column
                    title="序号"
                    type="index"
                    align="center"
                    width="55"
                    fixed
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="materialCode"
                    title="设备物资编码"
                    width="110"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="materialName"
                    title="设备物资名称"
                    width="300"
                    :formatter="handleFormatter"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="acceptCode"
                    title="验收单编号"
                    width="150"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="materialState"
                    title="设备型号说明"
                    width="130"
                    resizable
                >
                    <template slot-scope="{ row }">
                        <el-input v-model="row.materialState" v-if="row.isOtherCost == 1"/>
                        <span v-else>{{ row.materialState }}</span>
                    </template>
                </ux-table-column>
                
                <ux-table-column show-overflow-tooltip field="measureUnit" title="计量单位" min-width="100" resizable/>
                
                <ux-table-column
                    show-overflow-tooltip
                    field="acceptTime"
                    title="验收日期"
                    width="100"
                    resizable
                />
                
                <ux-table-column
                    show-overflow-tooltip
                    field="unTransportCount"
                    title="剩余可结算数量"
                    width="130"
                    resizable
                />
                
                <!--multiRateCode: 1 0. 是 1.否-->
                <ux-table-column
                    show-overflow-tooltip
                    field="taxRatePercent"
                    title="税率"
                    min-width="100"
                    resizable
                >
                    <template v-slot="{ row }">
                        <el-select
                            v-model="row.taxRateCode"
                            v-if="
                            isMultiRate == 0 &&
                              row.isOtherCost == 1
                          "
                            @change="
                                data => {
                                  handleTaxRate(data, row);
                                }
                              "
                        >
                            <el-option
                                v-for="item in taxRateOptions"
                                :key="item.dicKey"
                                :label="item.dicValue"
                                :value="item.dicKey"
                            />
                        </el-select>
                        <span v-else>{{
                                (row.taxRatePercent = isMultiRate ? isTaxRatePercent : row.taxRatePercent)
                            }}</span>
                    </template>
                </ux-table-column>
                
                <ux-table-column
                    show-overflow-tooltip
                    field="settlementCount"
                    title="结算数量"
                    width="100"
                    resizable
                    :edit-render="{autofocus: '.el-input__inner'}"
                >
                    <template v-slot:edit="{ row }">
                        <el-input
                            v-if="row.isOtherCost == 0 && row.isMerge == 0 && !row.isCategories"
                            v-model="row.settlementCount"
                            @input="check_number(row, 'settlementCount', 3)"
                            @blur="handleNum(row, 'settlementCount', 3)"
                        />
                        <span v-else>{{ row.settlementCount }}</span>
                    </template>
                    <template v-slot="{ row }">
                        <span
                            :class="{'my-input-sc': row.isOtherCost == 0 && row.isMerge == 0 && !row.isCategories}">{{
                                row.settlementCount
                            }}</span>
                    </template>
                </ux-table-column>
                
                <ux-table-column
                    show-overflow-tooltip
                    field="unitPriceWithTax"
                    title="含税单价"
                    width="130"
                    resizable
                    :edit-render="{autofocus: '.el-input__inner'}"
                >
                    <template v-slot:edit="{ row }">
                        <el-input v-if="isFloat == 0 && row.isOtherCost == 0 && !row.isCategories"
                                  v-model="row.unitPriceWithTax"
                                  @input="check_number(row, 'unitPriceWithTax', 2)"
                                  @blur="handleNum(row, 'unitPriceWithTax', 2)"
                        />
                        <span v-else> {{ row.unitPriceWithTax }}</span>
                    </template>
                    
                    <template v-slot="{ row }">
                        <span :class="{'my-input-sc':isFloat==0 && row.isOtherCost == 0 && !row.isCategories}">{{
                                row.unitPriceWithTax
                            }}</span>
                    </template>
                </ux-table-column>
                <ux-table-column
                    show-overflow-tooltip
                    field="moneyWithTax"
                    title="含税金额"
                    width="130"
                    resizable
                    :edit-render="{autofocus: '.el-input__inner'}"
                >
                    <template v-slot:edit="{ row }">
                        <el-input
                            v-if="
                            (row.isCategories && row.isCategories == 1) ||
                              row.isOtherCost == 1
                          "
                            v-model="row.moneyWithTax"
                            @input="check_number(row, 'moneyWithTax', 2)"
                            @blur="handleNum(row, 'moneyWithTax', 2)"
                        />
                        <span v-else>{{ row.moneyWithTax }}</span>
                    </template>
                    
                    <template v-slot="{ row }">
                        <span
                            :class="{'my-input-sc':(row.isCategories && row.isCategories == 1) || row.isOtherCost == 1}">{{
                                row.moneyWithTax
                            }}</span>
                    </template>
                </ux-table-column>
                <ux-table-column
                    show-overflow-tooltip
                    field="brand"
                    title="生产厂家/品牌"
                    width="130"
                    resizable
                >
                    <template v-slot="{ row }">
                        <span> {{ row.brand }}</span>
                    </template>
                </ux-table-column>
            </ux-grid>
        </div>
        <dialogTableSelect ref="dialogTableSelect" :title="selectTitleDialog" :table-data="dialogTableData"
                           :table-thead-options="dialogTheadOptions" @dialogSelectVal="dialogSelectVal"/>
    </div>
</template>

<script>
import dropdown from "@/basa/components/public_practice/dropdown";
import dialogTableSelect from "@/basa/components/public_practice/dialogTableSelect";
import {
    listAcceptanceCert,
    getEquipmnetInfoForSettlement,
    getAcceptanceCert
} from "@/app/settlement-management/equipment/api";
import {generateUUID} from "@/basa/utils";
import BigNumber from "bignumber.js";

export default {
    name: "tableList",
    props: {
        settlementForm: {
            type: Object,
            default: () => {
            }
        },
        // settlementList: {
        //     type: Array,
        //     default: () => []
        // }
    },
    components: {dropdown, dialogTableSelect},
    data() {
        return {
            selectTitleDialog: "选择合同",
            settlementList: [], // 表格数据
            dropdown: {
                mainTitle: "其他费用项",
                btnText: [
                    {
                        command: "贴息"
                    },
                    {
                        command: "价格追涨"
                        
                    },
                    {
                        command: "价格追跌"
                    },
                    {
                        command: "其他"
                    }
                ]
            },
            dialogTableData: [],
            dialogTheadOptions: [],
            theadOptions: {
                contractOptions: [
                    {type: "selection"},
                    {label: "序号", type: "index"},
                    {prop: "materialsCode", label: "设备物资编码", width: "200"},
                    {prop: "materialsName", label: "设备物资名称", width: "300"},
                    {prop: "matDescribe", label: "设备物资说明", width: "130"},
                    {prop: "currentMeasuringUnit", label: "计量单位", width: "90"},
                    {prop: "currentNum", label: "合同数量", width: "80"},
                    {prop: "currentUnitPriceIncludeTax", label: "含税单价", width: "130"}
                ],
                acceptOptions: [
                    {type: "selection"},
                    {label: "序号", type: "index"},
                    {prop: "acceptanceNumber", label: "验收单编号"},
                    {prop: "acceptanceName", label: "验收单名称"},
                    {prop: "acceptanceType", label: "验收单类型"},
                    {prop: "supplier", label: "供应商"},
                    {prop: "compilePeople", label: "验收人"},
                    {prop: "currentAcceptanceEndNumber", label: "实际验收数量"},
                    {prop: "compileDate", label: "编制日期"}
                ]
            },
            taxRateOptions: [],
            contractId: null,
            isFloat: null,
            isMultiRate: null,
            isTaxRatePercent: "",
            isTaxRate: null,
            isTaxRateCode: "",
            isContractCode: "",
            checkedLine: [],
            heBingCopy: [],
            merged: [],
            serveData: []
        }
    },
    watch: {
        settlementList(n) {
            this.handleTable();
        }
    },
    created() {
        this.$bus.$on("getContract", isJudgement => {
            this.settlementList = [];
            this.isFloat = isJudgement.isFloat;
            this.isMultiRate = isJudgement.isMultiRate;
            this.isTaxRate = isJudgement.isTaxRate;
            this.isTaxRateCode = isJudgement.isTaxRateCode;
            this.isTaxRatePercent = isJudgement.isTaxRatePercent;
            this.serveData = JSON.parse(JSON.stringify(isJudgement.serveData));
            this.settlementList.push(...this.serveData);
            this.contractId = isJudgement.concId;
            this.isContractCode = isJudgement.isContractCode
        });
        this.$bus.$on("getEditContract", isJudgement => {
            this.isFloat = isJudgement.isFloat;
            this.isMultiRate = isJudgement.isMultiRate;
            this.isTaxRate = isJudgement.isTaxRate;
            this.isTaxRateCode = isJudgement.isTaxRateCode;
            this.isTaxRatePercent = isJudgement.isTaxRatePercent;
            this.contractId = isJudgement.concId;
        });
    },
    methods: {
        //自动合并settlementList
        hebingFunAuto() {
            this.heBingCopy = JSON.parse(JSON.stringify(this.settlementList));
            let that = this;
            
            function getKey(item) {
                if (that.isFloat) {
                    // 1 固定价
                    return item.materialCode + item.materialName + item.materialState + item.unitPriceWithTax + item.brand + item.taxRatePercent
                } else {
                    return item.materialCode + item.materialName + item.materialState + item.brand + item.taxRatePercent
                }
            }
            
            this.heBingCopy = this.heBingCopy.filter(
                item =>
                    !(
                        (item.isMerge == 1 && item.isMainInventory == 0) ||
                        item.isOtherCost == 1 ||
                        item.isCategories == 1
                    )
            );
            var checkLineCount = {};
            for (var i = 0; i < this.heBingCopy.length; i++) {
                var count = checkLineCount[getKey(this.heBingCopy[i])];
                if (count == null) {
                    checkLineCount[getKey(this.heBingCopy[i])] = 1;
                } else {
                    checkLineCount[getKey(this.heBingCopy[i])] += 1;
                }
            }
            for (var j = 0; j < Object.keys(checkLineCount).length; j++) {
                this.hebingFunAutoAtom(
                    this.heBingCopy.filter(
                        item => getKey(item) == Object.keys(checkLineCount)[j]
                    )
                );
            }
            this.$refs["tableList"].clearSelection();
        },
        // 合并
        hebingFunAutoAtom(checkedLine) {
            checkedLine = checkedLine.filter(
                item => !(item.isMerge == 1 && item.isMainInventory == 0)
            );
            if (checkedLine.length == 1) return;
            var settlementCount = 0;
            var moneyWithTax = 0;
            var unTransportCount = 0;
            var oldUuidSet = new Set();
            var mergeItem = JSON.parse(JSON.stringify(checkedLine[0]));
            for (let i = 0; i < checkedLine.length; i++) {
                oldUuidSet.add(checkedLine[i].mergeUuid);
                if (checkedLine[i].isMainInventory == 1) {
                    this.settlementList.forEach((item, index) => {
                        if (
                            item.mergeUuid == checkedLine[i].mergeUuid &&
                            item.isMainInventory == 1
                        ) {
                            if (!this.merged.includes(item.mergedId) || unTransportCount == 0) {
                                unTransportCount = (+unTransportCount + +item.unTransportCount).toFixed(3);
                                this.merged.push(item.mergedId);
                            } else {
                                if (Number(unTransportCount) < Number(item.unTransportCount)) {
                                    unTransportCount = item.unTransportCount;
                                }
                            }
                            // acceptCount = (+acceptCount + +item.acceptCount).toFixed(3);
                            moneyWithTax = (+moneyWithTax + +item.moneyWithTax).toFixed(3);
                            this.settlementList.splice(index, 1);
                        }
                    });
                }
            }
            var newUuid = generateUUID();
            // 把第一条数据的合并标识位与主数据标识变为1
            mergeItem.isMerge = 1;
            mergeItem.isMainInventory = 1;
            mergeItem.mergeUuid = newUuid;
            let isMainInventoryMerged = mergeItem.isMainInventoryMerged ? mergeItem.isMainInventoryMerged.split(',') : [];
            for (let i = 0; i < this.settlementList.length; i++) {
                if (!this.settlementList[i].isShow) {
                    if (oldUuidSet.has(this.settlementList[i].mergeUuid)) {
                        this.settlementList[i].isMerge = 1;
                        this.settlementList[i].isMainInventory = 0;
                        if (
                            !this.merged.includes(this.settlementList[i].mergedId) ||
                            unTransportCount == 0
                        ) {
                            unTransportCount = (
                                +unTransportCount + +this.settlementList[i].unTransportCount
                            ).toFixed(3);
                            this.merged.push(this.settlementList[i].mergedId);
                            isMainInventoryMerged.push(this.settlementList[i].mergedId);
                        } else {
                            if (Number(unTransportCount) < Number(this.settlementList[i].unTransportCount)) {
                                unTransportCount = this.settlementList[i].unTransportCount;
                            }
                        }
                        settlementCount = (+settlementCount + +this.settlementList[i].settlementCount).toFixed(3);
                        moneyWithTax = (+moneyWithTax + +this.settlementList[i].moneyWithTax).toFixed(2);
                        this.settlementList[i].moneyWithTax = 0; // 必须得等于0，不然合计不正确
                        this.settlementList[i].mergeUuid = newUuid;
                    }
                }
            }
            if (!this.isFloat) {
                mergeItem.unitPriceWithTax = "";
            }
            mergeItem.isMainInventoryMerged = isMainInventoryMerged.join(",");
            mergeItem.acceptCode = "";
            mergeItem.acceptanceCode = "";
            mergeItem.settlementCount = settlementCount;
            mergeItem.moneyWithTax = moneyWithTax;
            mergeItem.unTransportCount = unTransportCount;
            mergeItem.isShow = true;
            console.log(mergeItem, 'mergeItem');
            this.settlementList.push(mergeItem);
            this.settlementList.splice();
        },
        dialogSelectVal(selectVal) {
            /**
             * serveData 服务类数据存起来
             * 通过验收单acceptCode判断 选中的数据与表格数据
             * 验收单调接口 合同直接push
             * */
            
            // 判断选中数据, source  0合同   1验收
            let selectBool = selectVal.every(e => e.source == 1);
            // 调用验收单入参ids
            let ids = selectVal.map(item => item.id);
            let emptyBool = this.settlementList.filter(e => !e.isCategories).length;
            if (emptyBool) {
                // 非空 选中数据与表格数据对比是否同类
                let tableBool = this.settlementList.filter(item => !item.isCategories).every(e => e.source == 1);
                // tableBool true 表格内数据为验收 false 为合同
                if (tableBool != selectBool) {
                    this.settlementList = this.settlementList.filter(e => e.isCategories);
                }
                if (selectBool) {
                    this.getAcceptanceCert(ids)
                } else {
                    this.settlementList.push(...selectVal);
                }
                // 同类 push
                // 非同类 清空 + push
            } else {
                // 除服务类无其他数据, 向表格进行push操作
                if (!selectVal.length) return this.$refs["dialogTableSelect"].dialogVisible = false;
                // acceptCodeBool false 代表合同 true 代表验收
                if (selectBool) {
                    this.getAcceptanceCert(ids);
                } else {
                    this.settlementList.push(...selectVal);
                }
            }
            this.settlementList.forEach(e => {
                this.check_number(e);
            });
            this.$refs["dialogTableSelect"].dialogVisible = false;
        },
        // 验收单id查询详情
        getAcceptanceCert(id, serveArray = []) {
            getAcceptanceCert({ids: id, businessType: "3"}).then(res => {
                let result = res.data.data;
                result.forEach(_ => {
                    _.source = 1;
                    if (this.settlementForm.smpConcMatLessListBOS) {
                        var contractItem = this.settlementForm.smpConcMatLessListBOS.find(
                            data => data.firstId == _.materialFirstId
                        );
                        if (!contractItem) {
                            _.unitPriceWithTax = "";
                            _.taxRate = "";
                        } else {
                            if (!this.isFloat) {
                                _.unitPriceWithTax = "";
                            } else {
                                _.unitPriceWithTax = contractItem.currentUnitPriceIncludeTax
                                    ? (+contractItem.currentUnitPriceIncludeTax).toFixed(2)
                                    : "";
                            }
                        }
                    }
                    
                    this.$set(
                        _,
                        "taxRate",
                        this.settlementForm.smpPcConcBO.multiRateCode
                            ? this.settlementForm.smpPcConcBO.taxRate / 100
                            : contractItem.taxRate
                    );
                    this.$set(
                        _,
                        "taxRateCode",
                        this.settlementForm.smpPcConcBO.multiRateCode
                            ? this.settlementForm.smpPcConcBO.taxRateCode
                            : contractItem.taxRateCode
                    );
                    this.$set(
                        _,
                        "taxRatePercent",
                        this.settlementForm.smpPcConcBO.multiRateCode
                            ? this.settlementForm.smpPcConcBO.taxRatePercent
                            : contractItem.taxRatePercent
                    );
                    _.isMerge = 0;
                    _.isMainInventory = 0;
                    _.isOtherCost = 0;
                    _.isServices = 0;
                    _.costStatus = 0;
                    _.acceptName = _.acceptanceName;
                    // 结算数量刚进来默认 = 剩余可结算数量
                    _.unTransportCount = (+_.residualSettlementNumber).toFixed(3);
                    _.settlementCount = _.unTransportCount;
                    _.acceptTime = _.acceptanceDate ? _.acceptanceDate.substr(0, 10) : "";
                    _.acceptCode = _.acceptanceCode;
                    // 修改验收数量字段 acceptCount
                    _.acceptCount = new BigNumber(+_.acceptanceCurrentNumber).minus(+_.bowOutCurrentNumber).toFixed(3);
                    _.brand = _.manufacturerBrand;
                    let moneyWithTax = (
                        _.unitPriceWithTax * _.settlementCount
                    ).toFixed(2);
                    this.$set(_, "moneyWithTax", moneyWithTax);
                    _.moneyWithoutTax = "";
                    _.unitPriceWithoutTax = "";
                    _.remarks = _.remake;
                    _.contractCode = this.isContractCode;
                    
                    _.acceptId = _.acceptanceId;
                    // 后端新加验收单acceptListId
                    _.acceptListId = _.id;
                    _.firstId = _.materialFirstId;
                    //加mergedId用于判断是否剩余数量被累加
                    _.mergedId = _.id;
                    _.mergeUuid = generateUUID();
                });
                // serveArray?this.settlementList.push(...mockData, ...serveArray) : this.settlementList.push(...mockData);
                console.log(result, 'result');
                this.settlementList.push(...result, ...serveArray);
                // let ids = this.settlementList.map(e => e.id);
                // console.log(ids, 'ids');
            });
        },
        handleTaxRate(val, row) {
            let taxRate = this.taxRateOptions.find(e => e.dicKey == val).dicValue;
            taxRate = taxRate == "免税" ? 0 : taxRate.split("%")[0] / 100;
            let taxRatePercent = this.taxRateOptions.find(e => e.dicKey == val)
                .dicValue;
            this.$set(row, "taxRate", taxRate);
            this.$set(row, "taxRa" +
                "tePercent", taxRatePercent);
            
            let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
                .dividedBy(1 + +row.taxRate)
                .toNumber()
                .toFixed(2);
            this.$set(row, "moneyWithoutTax", moneyWithoutTax);
        },
        // 计算含税金额 start
        check_number(row, prop, num) {
            let reg =
                row.materialName == "价格追跌" ||
                row.materialName == "贴息" ||
                row.materialName == "其他"
                    ? /^-?\d*\.?\d*$/
                    : /^\d*\.?\d*$/;
            if (reg.test(row[prop])) {
                const arr = row[prop].split(".");
                if (arr[arr.length - 1].length > num && arr.length == 2) {
                    row[prop] = row[prop].substr(0, row[prop].length - 1);
                } else if (arr.length == 1 && row[prop].length > 12) {
                    this.$message.warning("整数最多可以输入12位");
                    row[prop] = row[prop].substr(0, row[prop].length - 1);
                }
            } else if (
                row[prop] &&
                reg.test(row[prop].substr(0, row[prop].length - 1))
            ) {
                row[prop] = row[prop].substr(0, row[prop].length - 1);
            } else {
                row[prop] = "";
            }
            // moneyWithoutTax 不含税金额(元) unitPriceWithoutTax 不含税单价(元)
            if (
                row.materialName == "价格追跌" &&
                row[prop][0] != "-" &&
                row[prop] != ""
            ) {
                row[prop] = 0 - Math.abs(+row[prop]);
            }
            
            if (row.settlementCount !== "" && row.unitPriceWithTax !== "") {
                let moneyWithTax = new BigNumber(+row.settlementCount)
                    .multipliedBy(+row.unitPriceWithTax).toFixed(2)
                this.$set(row, "moneyWithTax", moneyWithTax);
                
                let unitPriceWithoutTax = new BigNumber(+row.unitPriceWithTax)
                    .dividedBy(1 + +row.taxRate)
                    .toFixed(2);
                this.$set(row, "unitPriceWithoutTax", unitPriceWithoutTax);
                let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
                    .dividedBy(1 + +row.taxRate)
                    .toFixed(2);
                this.$set(row, "moneyWithoutTax", moneyWithoutTax);
            }
            
            if ((row.isOtherCost && row.taxRate) || row.isCategories) {
                // this.$set(row, "moneyWithTax", row.moneyWithTax);
                
                let moneyWithoutTax = new BigNumber(+row.moneyWithTax)
                    .dividedBy(1 + +row.taxRate)
                    .toFixed(2);
                this.$set(row, "moneyWithoutTax", moneyWithoutTax);
            }
            
        },
        // 处理input失焦数据格式
        handleNum(row, name, toFix) {
            if (row[name] == "-") return (row[name] = "");
            if (name == "unitPriceWithTax" && row.isMerge == 1 && row.isMainInventory == 1) {
                this.settlementList.map(e => {
                    if (row.mergeUuid == e.mergeUuid) {
                        e.unitPriceWithTax = row.unitPriceWithTax
                    }
                })
            }
            row[name] = (+row[name]).toFixed(toFix);
        },
        // 获取选中
        handleSelectionChange(val) {
            console.log(val, 'handleSelectionChange');
            // this.checkedLine = val;
        },
        // 选中数据
        selectTable(val) {
            this.checkedLine = val;
        },
        handleSelectableDisabled({row}) {
            return row.isCategories !== 1
        },
        chooseSelectDialog(type) {
            if (!this.settlementForm.contractCode) return this.$showErrorMessage("请选择合同编号");
            this.dialogTableData = [];
            if (type === "contract") {
                this.selectTitleDialog = "选择合同";
                this.dialogTheadOptions = this.theadOptions.contractOptions;
                this.$route.query.id ? this.getContract(this.settlementForm.contractId) : this.getContract(this.contractId);
            } else if (type === "accept") {
                this.selectTitleDialog = "选择验收单";
                this.dialogTheadOptions = this.theadOptions.acceptOptions;
                this.getAccept();
            }
            this.$refs["dialogTableSelect"].dialogVisible = true;
        },
        // 验收单
        getAccept() {
            let params = {
                contractNumber: this.settlementForm.contractCode,
                moduleType: "settlement",
                businessType: "3",
                reportInOrgId: this.settlementForm.reportInOrgId,
            };
            listAcceptanceCert(params).then(res => {
                res.data.data.forEach(item => {
                    item.compileDate = item.compileDate ? item.compileDate.substr(0, 10) : "";
                    item.acceptCode = item.acceptanceNumber;
                    item.source = 1;
                });
                this.dialogTableData = res.data.data;
            });
        },
        // 合同
        getContract(id) {
            if (!id) return this.$showErrorMessage("合同ID不能为空");
            getEquipmnetInfoForSettlement({concId: id}).then(res => {
                let result = res.data.data;
                let arr = ["1305", "1306", "1307", "1308", "1309", "990103"];
                let filterServeData = result.smpConcMatLessListBOS.filter(item => {
                    item.source = 0;
                    item.categoryCode = item.thirdCategoriesOfCode;
                    item.isMerge = 0;
                    item.isMainInventory = 0;
                    item.isOtherCost = 0;
                    item.isServices = 0;
                    item.costStatus = 0;
                    item.materialCode = item.materialsCode;
                    item.materialName = item.materialsName;
                    item.materialState = item.matDescribe;
                    item.measureUnit = item.currentMeasuringUnit;
                    // 结算数量刚进来默认 = 剩余可结算数量
                    item.unTransportCount = (+item.residualSettlementNumber).toFixed(3);
                    item.settlementCount = item.unTransportCount;
                    item.acceptTime = item.acceptanceDate ? item.acceptanceDate.substr(0, 10) : "";
                    item.acceptCode = item.acceptanceCode;
                    // 修改验收数量字段 acceptCount
                    item.unitPriceWithTax = (+item.baseUnitPriceIncludeTax).toFixed(2);
                    item.acceptCount = "";
                    item.brand = item.manufacturer;
                    let moneyWithTax = (
                        item.unitPriceWithTax * item.settlementCount
                    ).toFixed(2);
                    this.$set(item, "moneyWithTax", moneyWithTax);
                    
                    item.moneyWithoutTax = "";
                    item.unitPriceWithoutTax = "";
                    item.acceptId = item.acceptanceId;
                    // 后端新加验收单acceptListId
                    item.materialId = item.id;
                    item.materialFirstId = item.firstId;
                    //加mergedId用于判断是否剩余数量被累加
                    item.mergedId = item.id;
                    
                    item.mergeUuid = generateUUID();
                    return !arr.some(_item => item.thirdCategoriesOfCode.startsWith(_item));
                });
                this.dialogTableData = filterServeData;
            });
        },
        // 汇总
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums.push("合计");
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr, rowIndex) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            if (column.title == "结算数量") {
                                return new BigNumber(+prev).plus(+curr).toString();
                            } else if (column.title == "含税金额") {
                                if (
                                    data[rowIndex].isMerge == 1 &&
                                    data[rowIndex].isMainInventory == 0
                                ) {
                                    return prev;
                                }
                                return new BigNumber(+prev).plus(+curr).toString();
                            } else {
                                return (prev = " ");
                            }
                        } else {
                            return (prev = " ");
                        }
                    }, 0);
                    if (column.title == "结算数量") {
                        sums[index] = (+sums[index]).toFixed(3);
                    }
                    if (column.title == "含税金额") {
                        sums[index] = (+sums[index]).toFixed(2);
                    }
                } else {
                    sums[index] = "";
                }
                // 基本信息的结算数量和结算金额根据结算单明细的结算数量和含税金额同步
                this.settlementForm.currSetCount = sums[10] == 0 ? "" : sums[10];
                this.settlementForm.currSetMoney = sums[12];
                this.$emit("childTableData", this.settlementList);
            });
            return [sums];
        },
        handleFormatter({row}) {
            if (
                row.materialName == "贴息" ||
                row.materialName == "价格追涨" ||
                row.materialName == "价格追跌" ||
                row.materialName == "其他" ||
                (row.categoryCode &&
                    row.categoryCode.substr(0, 4) ==
                    ("1305" || "1306" || "1307" || "1308" || "1309")) ||
                row.categoryCode.substr(0, 6) == "990103"
            ) {
                let arr = ["unTransportCount", "settlementCount", "unitPriceWithTax"];
                arr.forEach(e => {
                    row[e] = "";
                });
            }
            return row.materialName;
        },
        handleTable() {
            if (this.settlementList.length) {
                let yunshu = [], // 运输类
                    hebingqian = [], // 没有合并的数据
                    hebinghou = [], // 合并后隐藏的数据
                    hebingMerge = [], // 合并后生成的数据
                    qita = []; // 其他类数据
                this.settlementList.map(e => {
                    if (e.isCategories && e.isCategories == 1) {
                        yunshu.push(e);
                    } else if (e.isMerge == 0 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebingqian.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebinghou.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 1 && e.isOtherCost == 0) {
                        hebingMerge.push(e);
                    } else if (e.isOtherCost && e.isOtherCost == 1) {
                        qita.push(e);
                    }
                });
                let tableData = [...hebingqian, ...hebingMerge, ...yunshu, ...qita];
                this.$refs["tableList"].reloadData(tableData);
            } else {
                this.$refs["tableList"].reloadData([]);
            }
        },
        // 其他费用
        dropDown(val) {
            if (!this.settlementList.length) return this.$showErrorMessage("请先选择合同或验收单");
            if (this.settlementList.find(row => row.materialName == val && row.isOtherCost == 1) != null) {
                this.$message({
                    type: "warning",
                    message: "该类型已存在"
                });
                return;
            }
            let obj = {
                mergeUuid: generateUUID(),
                materialName: val,
                materialState: "",
                acceptNumber: "isOtherCost",
                isMerge: 0,
                isMainInventory: 0,
                isServices: 0,
                isOtherCost: 1,
                costName: val,
                costStatus: 1,
                acceptCount: null,
                unTransportCount: null,
                settlementCount: "",
                unitPriceWithTax: "",
                moneyWithTax: null,
                moneyWithoutTax: null,
                taxRate: this.isMultiRate
                    ? this.isTaxRate / 100
                    : "",
                taxRateCode: this.isMultiRate
                    ? this.isTaxRateCode
                    : "",
                isTaxRatePercent: this.isMultiRate
                    ? this.isTaxRatePercent
                    : ""
            };
            this.settlementList.push({...obj});
        },
        //删除行
        handleDelete() {
            if (this.checkedLine.length < 1) {
                this.$message.warning("请选择一项");
                return;
            }
            var mergeUuidSet = new Set();
            
            let that = this;
            
            function removeMerged(val) {
                for (var j = 0; j < that.merged.length; j++) {
                    if (that.merged[j] == val) that.merged[j] = "";
                }
            }
            
            
            for (var i = 0; i < this.checkedLine.length; i++) {
                //删除行，去掉已合并的id记录，id为标记是否在结算中参加了剩余可结算量的操作，避免重复剩余可结算量的累加
                if (this.checkedLine[i].isMainInventoryMerged) {
                    
                    this.checkedLine[i].isMainInventoryMerged.split(",").forEach(n => {
                        removeMerged(n);
                    });
                } //删除标记结束
                mergeUuidSet.add(this.checkedLine[i].mergeUuid);
            }
            for (i = this.settlementList.length - 1; i >= 0; i--) {
                if (mergeUuidSet.has(this.settlementList[i].mergeUuid)) {
                    this.settlementList.splice(i, 1);
                }
            }
        },
    },
    mounted() {
        let that = this
        
        function mergedJoin(str) {
            let arr = []
            that.settlementList.forEach(obj => {
                if (obj.materialCode + obj.materialState + obj.measureUnit + obj.brand == str) {
                    arr.push(obj.acceptListId)
                }
            })
            return arr.join(',')
        }
        
        if (this.$route.params.id) {
            this.settlementList.forEach(item => {
                if (item.isMainInventory == 1) {
                    item.isMainInventoryMerged = mergedJoin(item.materialCode + item.materialState + item.measureUnit + item.brand)
                }
                if (item.isMerge == 1) {
                    this.merged.push(item.acceptListId);
                }
            });
        }
    },
    destroyed() {
        this.$bus.$off("getContract");
    }
}
</script>

<style scoped lang="scss">
.operation-group {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 20px;
}

/deep/ .el-dropdown {
    margin-right: 10px;
    
    button {
        background: #f7f9ff;
        border: 1px solid #0089ef;
        color: #0089ef;
    }
}
</style>